package com.linsen.core.ohc.serializer;

import com.google.common.base.Charsets;
import org.caffinitas.ohc.CacheSerializer;

import java.nio.ByteBuffer;

/**
 * @author zhaoyong
 * @date 2023/3/30
 */
public class StringCacheSerializer implements CacheSerializer<String> {
    public final static StringCacheSerializer INSTANCE = new StringCacheSerializer();

    @Override
    public void serialize(String s, ByteBuffer byteBuffer) {
        // 得到字符串对象UFT8编码的字节数组
        byte[] bytes = s.getBytes(Charsets.UTF_8);
        // 用前6位记录数组长度
        byteBuffer.put((byte) ((bytes.length >>> 8) & 0xFF));
        byteBuffer.put((byte) ((bytes.length) & 0xFF));
        byteBuffer.put(bytes);
    }

    @Override
    public String deserialize(ByteBuffer byteBuffer) {
        // 获取字节数组的长度
        int length = ((byteBuffer.get() & 0xff) << 8) + ((byteBuffer.get() & 0xff));
        byte[] bytes = new byte[length];
        // 读取字节数组
        byteBuffer.get(bytes);
        // 返回字符串对象
        return new String(bytes, Charsets.UTF_8);
    }

    @Override
    public int serializedSize(String s) {
        byte[] bytes = s.getBytes(Charsets.UTF_8);
        // 设置字符串长度限制
        if (bytes.length > 65536) {
            throw new RuntimeException("encoded string too long " + bytes.length + " bytes");
        }

        return bytes.length + 2;
    }
}